package com.example.a13001.shoppingmalltemplate.fragments;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.example.a13001.shoppingmalltemplate.R;
import com.example.a13001.shoppingmalltemplate.ZprogressHud.ZProgressHUD;
import com.example.a13001.shoppingmalltemplate.activitys.GoodsDetailActivity;
import com.example.a13001.shoppingmalltemplate.activitys.GoodsListActivity;
import com.example.a13001.shoppingmalltemplate.adapters.ClassifyLvAdapterSanji;
import com.example.a13001.shoppingmalltemplate.adapters.ClassifyTwoLvAdapter;
import com.example.a13001.shoppingmalltemplate.adapters.ClassifyfGvAdapter;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.modle.Classify;
import com.example.a13001.shoppingmalltemplate.modle.GoodsList;
import com.example.a13001.shoppingmalltemplate.modle.Special;
import com.example.a13001.shoppingmalltemplate.mvpview.ClassifyView;
import com.example.a13001.shoppingmalltemplate.presenter.ClassifyPredenter;
import com.example.a13001.shoppingmalltemplate.utils.GlideUtils;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ClassifyFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ClassifyFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    Unbinder unbinder;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private ListView mLvClassify;
    private GridView mGvErJi;
    private GridView mGvErJi1;
    private ListView mLvClassifyRight;
    private ImageView mIvLogo;
    private ImageView mIvBack;

    private List<Classify.ListBeanXX> mList;
    private List<Classify.ListBeanXX.ListBeanX> mListTitle1;
    private List<GoodsList.ListBean> mListTitle;

    private ClassifyfLvAdapter mAdapter;
    private ClassifyfGvAdapter mAdaperErJi;
    private ClassifyTwoLvAdapter mAdaperErJiTwo;
    private ClassifyLvAdapterSanji mAdaperSanJi;



    private String elite = "";
    private String xinpin = "";
    private String order = "";


    //    private NewClassfyLvAdapter1 mAdapterRight1;
    //    private NewClassfyLvAdapter mAdapterRight;
    //    private List<Special.ListBean> mListRight1;
    //    private List<HomePageTitle> mListRight;
    private static final String TAG = "ClassifyFragment";
    private int pageindex1=1;
    private int pageindex = 1;
    private int currentItemPosition = 0;//一级分类当前位置
    private boolean ifSanji=false;
    ClassifyPredenter classifyPredenter = new ClassifyPredenter(getActivity());
    private ZProgressHUD zProgressHUD;
    public ClassifyFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ClassifyFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ClassifyFragment newInstance(String param1, String param2) {
        ClassifyFragment fragment = new ClassifyFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_classify, container, false);

        initView(view);
        initData();
        unbinder = ButterKnife.bind(this, view);
        zProgressHUD=ZProgressHUD.getInstance(getActivity());
        zProgressHUD.show();


        //获取资讯列表
        classifyPredenter.getClassifyList(AppConstants.COMPANY_ID, AppConstants.CLASSIFY_ID);
//        classifyPredenter.getSpecialList(AppConstants.COMPANY_ID,AppConstants.CLASSIFY_ID,"","",AppConstants.PAGE_SIZE,pageindex1);

        return view;
    }

    ClassifyView classifyView = new ClassifyView() {
        //获取一级分类
        @Override
        public void onSuccess(Classify mClassify) {
            Log.e(TAG, "onSuccess: "+mClassify.toString() );
            zProgressHUD.dismiss();
            int status = mClassify.getStatus();
            if (status > 0) {

                mList.addAll(mClassify.getList());
                mAdapter.notifyDataSetChanged();
                if (!TextUtils.isEmpty(mClassify.getList().get(0).getMobileclassImages())){
                    mIvLogo.setVisibility(View.VISIBLE);
                    GlideUtils.setNetImage2(getActivity(),AppConstants.INTERNET_HEAD+mClassify.getList().get(0).getMobileclassImages(),mIvLogo);
                }else{
                    mIvLogo.setVisibility(View.GONE);
                }

                    int iii=0;
                if (mList.get(0).getClassCount()>0){
                    for (int i = 0; i < mList.get(0).getList().size(); i++) {
                       iii+=mList.get(0).getList().get(i).getClassCount();
                    }
                    if (iii==0){
                        ifSanji=false;
                    }else{
                        ifSanji=true;
                    }
                        if (ifSanji){
                            mLvClassifyRight.setVisibility(View.VISIBLE);
                            mGvErJi.setVisibility(View.GONE);
                            mGvErJi1.setVisibility(View.GONE);
                            if (mListTitle1 != null) {
                                mListTitle1.clear();
                            }
                            mListTitle1.addAll(mClassify.getList().get(0).getList());
                            mAdaperSanJi=new ClassifyLvAdapterSanji(getActivity(),mListTitle1);
                            mLvClassifyRight.setAdapter(mAdaperSanJi);
                        }else{
                            mLvClassifyRight.setVisibility(View.GONE);
                            mGvErJi.setVisibility(View.VISIBLE);
                            mGvErJi1.setVisibility(View.GONE);

                            mListTitle1.addAll(mClassify.getList().get(0).getList());
                            mAdaperErJi=new ClassifyfGvAdapter(getActivity(),mListTitle1);
                            mGvErJi.setAdapter(mAdaperErJi);
                        }




                }else{
                    mLvClassifyRight.setVisibility(View.GONE);
                    mGvErJi.setVisibility(View.GONE);
                    mGvErJi1.setVisibility(View.VISIBLE);
                    if (mListTitle != null) {
                        mListTitle.clear();
                    }
                    if (mListTitle1 != null) {
                        mListTitle1.clear();
                    }

                    classifyPredenter.getGoodList(AppConstants.COMPANY_ID,AppConstants.CLASSIFY_ID, String.valueOf(mList.get(0).getClassid()),elite,xinpin,order,AppConstants.PAGE_SIZE,pageindex);
                    mGvErJi1.setAdapter(mAdaperErJiTwo);
                }

            } else {
                Toast.makeText(getActivity(), "" + mClassify.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }
        }

        //获取商品列表
        @Override
        public void onSuccessGoodsList(GoodsList mGoodsList) {
            Log.e(TAG, "onSuccessGoodsList: "+mGoodsList.toString());
            zProgressHUD.dismiss();
            int status = mGoodsList.getStatus();
            if (status > 0) {

                mListTitle.addAll(mGoodsList.getList());
                mAdaperErJiTwo.notifyDataSetChanged();
                mGvErJi1.setAdapter(mAdaperErJiTwo);
            } else {
                if (mListTitle != null) {
                    mListTitle.clear();
                    mAdaperErJiTwo.notifyDataSetChanged();
                    mGvErJi1.setAdapter(mAdaperErJiTwo);
                }
            }
        }

        /**
         * 专题列表
         * @param special
         */
        @Override
        public void onSuccessGetSpecialList(Special special) {
            zProgressHUD.dismiss();
            Log.e(TAG, "onSuccessGetSpecialList: "+special.toString() );
            int status=special.getStatus();
            if (status>0){
//                mListRight1.addAll(special.getList());
//                mAdapterRight.notifyDataSetChanged();
            }else{

            }
        }

        @Override
        public void onError(String result) {
            Log.e(TAG, "onError: "+result );
            zProgressHUD.dismissWithFailure();
        }
    };

    /**
     * 初始化数据源
     */
    private void initData() {
        classifyPredenter.onCreate();
        classifyPredenter.attachView(classifyView);


        /**
         * 分类列表
         */
        mList = new ArrayList<>();
        mListTitle = new ArrayList<>();
        mListTitle1 = new ArrayList<>();

//        mListRight = new ArrayList<>();
//        mListRight1 = new ArrayList<>();


//        mAdapterRight = new NewClassfyLvAdapter(getActivity(), mListRight1);
//        mLvClassifyRight.setAdapter(mAdapterRight);

//        mAdaperErJi = new ClassifyfGvAdapter(getActivity(), mListTitle);
        mAdaperErJiTwo = new ClassifyTwoLvAdapter(getActivity(), mListTitle);
        mAdapter = new ClassifyfLvAdapter(getActivity(), mList);
        mLvClassify.setAdapter(mAdapter);
        mLvClassify.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                currentItemPosition = position;
                mAdapter.notifyDataSetChanged();
                if (!TextUtils.isEmpty(mList.get(position).getMobileclassImages())){
                    mIvLogo.setVisibility(View.VISIBLE);
                    GlideUtils.setNetImage2(getActivity(),AppConstants.INTERNET_HEAD+mList.get(position).getMobileclassImages(),mIvLogo);
                }else{
                    mIvLogo.setVisibility(View.GONE);
                }
                int iii=0;
                if (mList.get(position).getClassCount()>0){
                    for (int i = 0; i < mList.get(position).getList().size(); i++) {
                        iii+=mList.get(position).getList().get(i).getClassCount();
                    }
                    if (iii==0){
                        ifSanji=false;
                    }else{
                        ifSanji=true;
                    }
                    if (ifSanji){
                        mLvClassifyRight.setVisibility(View.VISIBLE);
                        mGvErJi.setVisibility(View.GONE);
                        mGvErJi1.setVisibility(View.GONE);
                        if (mListTitle1 != null) {
                            mListTitle1.clear();
                        }
                        mListTitle1.addAll(mList.get(position).getList());
                        mAdaperSanJi=new ClassifyLvAdapterSanji(getActivity(),mListTitle1);
                        mLvClassifyRight.setAdapter(mAdaperSanJi);
                    }else{
                        mLvClassifyRight.setVisibility(View.GONE);
                        mGvErJi.setVisibility(View.VISIBLE);
                        mGvErJi1.setVisibility(View.GONE);
                        mGvErJi.setNumColumns(3);
                        if (mListTitle1 != null) {
                            mListTitle1.clear();
                        }
                        mListTitle1.addAll(mList.get(position).getList());
                        mAdaperErJi=new ClassifyfGvAdapter(getActivity(),mListTitle1);
                        mGvErJi.setAdapter(mAdaperErJi);
                    }


                }else{
                    zProgressHUD=ZProgressHUD.getInstance(getActivity());
                    zProgressHUD.show();
                    mLvClassifyRight.setVisibility(View.GONE);
                    mGvErJi.setVisibility(View.GONE);
                    mGvErJi1.setVisibility(View.VISIBLE);
                    if (mListTitle1 != null) {
                        mListTitle1.clear();
                    }

                    if (mListTitle != null) {
                        mListTitle.clear();
                    }
                    classifyPredenter.getGoodList(AppConstants.COMPANY_ID,AppConstants.CLASSIFY_ID, String.valueOf(mList.get(position).getClassid()),elite,xinpin,order,AppConstants.PAGE_SIZE,pageindex);

                }


            }
        });

        /**
         * 二级分类列表
         */
        mGvErJi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent=new Intent(getActivity(),GoodsListActivity.class);
                intent.putExtra("id",mListTitle1.get(i).getClassid());
                intent.putExtra("searchword","");
                startActivity(intent);
            }
        });

        mGvErJi1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                startActivity(new Intent(getActivity(), GoodsDetailActivity.class).putExtra("good_id", mListTitle.get(i).getId()));
            }
        });

    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initView(View view) {
        mLvClassify = (ListView) view.findViewById(R.id.lv_classifyf);
        mLvClassifyRight = (ListView) view.findViewById(R.id.lv_fenlei);
        mGvErJi = (GridView) view.findViewById(R.id.gv_classifyf_erji);
        mGvErJi1 = (GridView) view.findViewById(R.id.gv_classifyf_erji1);
        mIvBack = (ImageView) view.findViewById(R.id.iv_title_back);
        mIvLogo = (ImageView) view.findViewById(R.id.iv_classifyf_logo);
        mIvBack.setVisibility(View.GONE);

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    class ClassifyfLvAdapter extends BaseAdapter {
        private Context mContext;
        private List<Classify.ListBeanXX> mList;

        public ClassifyfLvAdapter(Context mContext, List<Classify.ListBeanXX> mList) {
            this.mContext = mContext;
            this.mList = mList;
        }

        @Override
        public int getCount() {
            if (mList != null) {
                return mList.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            if (mList != null && mList.size() > 0) {
                return mList.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_lv_classyfyf, parent, false);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
                AutoUtils.autoSize(convertView);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (position == currentItemPosition) {
                holder.llClassifyfitemBj.setBackgroundColor(getResources().getColor(R.color.white));
                holder.tvClassifyfitemName.setTextColor(getResources().getColor(R.color.black));
                holder.tvItemclassifyLine.setVisibility(View.VISIBLE);
            } else {
                holder.llClassifyfitemBj.setBackgroundColor(getResources().getColor(R.color.ec));
                holder.tvClassifyfitemName.setTextColor(getResources().getColor(R.color.a6d));
                holder.tvItemclassifyLine.setVisibility(View.GONE);
            }
            holder.tvClassifyfitemName.setText(mList.get(position).getClassName() != null ? mList.get(position).getClassName() : "");
            return convertView;
        }



        class ViewHolder {
            @BindView(R.id.tv_itemclassify_line)
            TextView tvItemclassifyLine;
            @BindView(R.id.tv_classifyfitem_name)
            TextView tvClassifyfitemName;
            @BindView(R.id.ll_classifyfitem_bj)
            LinearLayout llClassifyfitemBj;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }
}
